package com.inspector.app.ui.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

import com.inspector.app.R;

public class VideoPlayerView extends FrameLayout {

    private PlayerView playerView;
    private ExoPlayer player;

    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable hideUiRunnable = new Runnable() {
        @UnstableApi
        @Override
        public void run() {
            playerView.hideController();
        }
    };


    public VideoPlayerView(@NonNull Context context) {
        this(context, null);
    }

    public VideoPlayerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoPlayerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_video_player, this, true);
        playerView = findViewById(R.id.player_view);
    }


    public void initializePlayer(Context context, String videoUrl) {
        player = new ExoPlayer.Builder(context).build();
        playerView.setPlayer(player);
        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.play();

        // 设置监听器来检测播放状态
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_READY && player.getPlayWhenReady()) {
                    // 开始播放时，延迟3秒后隐藏UI
                    handler.postDelayed(hideUiRunnable, 1000);
                }
            }

            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                // 如果播放状态改变，取消之前的延迟任务
                handler.removeCallbacks(hideUiRunnable);
                if (isPlaying) {
                    // 再次尝试延迟3秒后隐藏UI
                    handler.postDelayed(hideUiRunnable, 1000);
                }
            }
        });


    }

    public void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
        }
    }
}
